import tim from '../../tim';
import TIM from 'tim-js-sdk';

const group = {
  state: {
    isAddGroupItemVisible: false,
    isGroupProfileInfoVisible: false,
    groupList: [],
    currentMemberList: [],
    currentGroupProfile: {},
    currentMemberListGroupID: '' // 当前群组成员列表对应的群组ID
  },
  mutations: {
    toggleIsAddGroupItemVisible(state,isAddGroupItemVisible){
      state.isAddGroupItemVisible = typeof isAddGroupItemVisible === 'undefined' ? !state.isAddGroupItemVisible : isAddGroupItemVisible;
    },
    toggleIsGroupProfileInfoVisible(state,isGroupProfileInfoVisible){
      state.isGroupProfileInfoVisible = typeof isGroupProfileInfoVisible === 'undefined' ? !state.isGroupProfileInfoVisible : isGroupProfileInfoVisible;
    },
    updateGroupList(state, groupList) {
      // 更新群组列表，调用时机：触发onGroupListUpdate回调
      state.groupList = groupList;
    },
    updateCurrentMemberList(state, currentMemberList) {
      state.currentMemberList = [...currentMemberList, ...state.currentMemberList];
      const ownerList = state.currentMemberList.filter(item => item.role === 'Owner');
      const adminList = state.currentMemberList.filter(item => item.role === 'Admin');
      const memberList = state.currentMemberList.filter(item => item.role === 'Member');
      state.currentMemberList = [... ownerList, ...adminList, ...memberList];
    },
    deleteCurrentMemberList(state, userIDList){
      // userIDList ['user0','user1']
      for(let i = 0; i < userIDList.length; i++){
        for(let currentMember = 0; currentMember < state.currentMemberList.length; currentMember++){
          if(userIDList[i] === state.currentMemberList[currentMember].userID){
            state.currentMemberList.splice(currentMember,1);
          }
        }
      }
    },
    updateCurrentGroupProfile(state, currentGroupProfile){
      state.currentGroupProfile = currentGroupProfile;
    },
    resetCurrentMemberList(state){
      state.currentMemberList = [];
    },
    reset(state){
      Object.assign(state, {
        isAddGroupItemVisible: false,
        isGroupProfileInfoVisible: false,
        groupList: [],
        currentMemberList: [],
        currentGroupProfile: {},
        currentMemberListGroupID: ''
      });
    }
  },
  actions: {
    createGroup(context,options){
      tim.createGroup(options).then(imResponse => {
        context.commit('updateCurrentGroupProfile', imResponse.data.group);
        context.dispatch('checkoutConversation', `GROUP${imResponse.data.group.groupID}`);
        context.commit('showMessage', { message: `群组：【${imResponse.data.group.name}】创建成功`, type: 'success' });
      }).catch(error => {
        context.commit('showMessage', { message: error.message , type: 'error' });
      });
    },
    joinGroup(context,options){
      tim.joinGroup(options).then(imResponse => {
        switch(imResponse.data.status) {
          case TIM.TYPES.JOIN_STATUS_WAIT_APPROVAL:
            context.commit('showMessage', { message: '申请成功，等待群管理员确认。', type: 'info' });
            break;
          case TIM.TYPES.JOIN_STATUS_SUCCESS:
            if(imResponse.data.group){
              context.commit('updateCurrentGroupProfile', imResponse.data.group);
              context.dispatch('checkoutConversation', `GROUP${imResponse.data.group.groupID}`);
            } else {
              // 游客登录时，只返回 imResponse.data.status === JOIN_STATUS_SUCCESS，需要手动更新当前会话ID
              context.commit('updateCurrentConversation', { conversationID: `GROUP${options.groupID}`, type: 'GROUP'});
            }
            context.commit('showMessage', { message: '加群成功', type: 'success' });
            break;
          case TIM.TYPES.JOIN_STATUS_ALREADY_IN_GROUP:
            context.commit('showMessage', { message: '您已经是群成员了，请勿重复加群哦！', type: 'info' });
            break;
          default: break;
        }
      }).catch(error => {
        context.commit('showMessage', { message: error.message, type: 'error' });
      });
    },
    quitGroup(context,groupID){
      tim.quitGroup(groupID).then(imResponse => {
        context.commit('resetCurrentConversation');
        context.commit('toggleIsGroupProfileInfoVisible', false);
        context.commit('showMessage', { message: `群组：【${imResponse.data.groupID}】退出成功`, type: 'success' });
      }).catch(error => {
        context.commit('showMessage', { message: error.message , type: 'error' });
      });
    },
    dismissGroup(context,groupID){
      tim.dismissGroup(groupID).then(imResponse => {
        context.commit('resetCurrentConversation');
        context.commit('toggleIsGroupProfileInfoVisible', false);
        context.commit('showMessage', { message: `群组：【${imResponse.data.groupID}】解散成功`, type: 'success' });
      }).catch(error => {
        context.commit('showMessage', { message: error.message , type: 'error' });
      });
    },
    setGroupMemberNameCard(context,options){
      // options { groupID: 'group1', userID: '可选，默认修改自身的群名片', nameCard: '用户名片' }
      tim.setGroupMemberNameCard(options).then(() => {
        context.commit('showMessage', { message: `设置群昵称成功`, type: 'success' });
      }).catch(error => {
        context.commit('showMessage', { message: error.message , type: 'error' });
      });
    },
    setMessageRemindType(context,options){
      // options { groupID: 'group1', messageRemindType: TIM.TYPES.MSG_REMIND_DISCARD } // 拒收消息
      tim.setMessageRemindType(options).then(() => {
        context.commit('showMessage', { message: `设置消息提示成功`, type: 'success' });
      }).catch(error => {
        context.commit('showMessage', { message: error.message , type: 'error' });
      });
    },
    getGroupMemberList(context, groupID) {
      tim.getGroupMemberList({
        groupID: groupID,
        offset: context.state.currentMemberList.length,
        count: 30
      }).then(({ data: { memberList }}) => {
        if(context.state.currentGroupProfile.groupID === groupID){ // 判断是否为当前群组，避免快速切换会话后才获取到资料，导致群组成员有误
          context.commit('updateCurrentMemberList', memberList);
          if(context.state.currentMemberList.length < context.state.currentGroupProfile.memberNum){
            context.dispatch('getGroupMemberList', groupID);
          }
        }
      }).catch(imError => {
        context.commit('showMessage', { message: imError.message , type: 'error' });
      });
    },
    getGroupMemberProfile(context,options){
      tim.getGroupMemberProfile(options).then(({ data: { memberList }}) => {
        context.commit('updateCurrentMemberList', memberList);
      }).catch(imError => {
        context.commit('showMessage', { message: imError.message , type: 'error' });
      });
    },
    addGroupMember(context,options){
      tim.addGroupMember(options).then(imResponse => {
        const {
          successUserIDList,
          failureUserIDList,
          existedUserIDList
        } = imResponse.data;
        if( successUserIDList.length > 0 ){
          context.commit('showMessage', { message: `群成员：${successUserIDList.join(',')}，加群成功`, type: 'success' });
          context.dispatch('getGroupMemberProfile', { groupID: imResponse.data.group.groupID, userIDList: successUserIDList });
        }
        if (failureUserIDList.length > 0) {
          context.commit('showMessage', { message: `群成员：${failureUserIDList.join(',')}，添加失败！`, type: 'error' });
        }
        if (existedUserIDList.length > 0) {
          context.commit('showMessage', { message: `群成员：${existedUserIDList.join(',')}，已在群中` });
        }
      }).catch(imError => {
        context.commit('showMessage', { message: imError.message , type: 'error' });
      });
    },
    updateGroupProfile(context,options){
      tim.updateGroupProfile(options).then(imResponse => {
        context.commit('updateCurrentGroupProfile', imResponse.data.group);
        context.commit('showMessage', { message: `群：${imResponse.data.group.name}，修改群资料成功`, type: 'success' });
      }).catch(imError => {
        context.commit('showMessage', { message: imError.message , type: 'error' });
      });
    },
    setGroupMemberRole(context,options){
      // options { groupID: 'group1',  userID: 'user1',  role: TIM.TYPES.GRP_MBR_ROLE_ADMIN // 将群 ID: group1 中的用户：user1 设为管理员 }
      tim.setGroupMemberRole(options).then(imResponse => {
        context.commit('showMessage', { message: `修改${imResponse.data.member.userID}角色成功`, type: 'success' });
      }).catch(imError => {
        context.commit('showMessage', { message: imError.message , type: 'error' });
      });
    },
    setGroupMemberMuteTime(context,options){
      // options { groupID: 'group1',  userID: 'user1',  muteTime: 600 // 禁言10分钟；设为0，则表示取消禁言 }
      tim.setGroupMemberMuteTime(options).then(imResponse => {
        let muteUntil = parseInt(imResponse.data.member.muteUntil - Date.now()/1000);
        if(muteUntil > 0){
          context.commit('showMessage', { message: `成员：${imResponse.data.member.userID}，禁言成功，禁言时间：${muteUntil}秒`, type: 'success' });
        } else {
          context.commit('showMessage', { message: `成员：${imResponse.data.member.userID}，取消禁言成功`, type: 'success' });
        }
      }).catch(imError => {
        context.commit('showMessage', { message: imError.message , type: 'error' });
      });
    },
    deleteGroupMember(context,options){
      // options {groupID: 'group1', userIDList:['user1'], reason: '踢人原因'}
      tim.deleteGroupMember(options).then(imResponse => {
        context.commit('deleteCurrentMemberList', imResponse.data.userIDList);
        context.commit('showMessage', { message: `移除成员：${imResponse.data.userIDList}成功`, type: 'success' });
      }).catch(imError => {
        context.commit('showMessage', { message: imError.message , type: 'error' });
      });
    }
  }
}

export default group;